<template>
  <div class="trigger-time-form">
    <el-form ref="triggerTimeFormRef" label-width="110px" :model="triggerTimeForm" :rules="rules" hide-required-asterisk>
      <el-form-item required>
        <template v-if="loopType === 0">
          <el-form-item label="指定日期：" prop="triggerAssignDate">
            <el-date-picker
              v-model="triggerTimeForm.triggerAssignDate"
              type="date"
              placeholder="选择日期"
              size="small"
              style="width: 65%"
              :disabled="shareData.isDisable"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleChange"
            />
          </el-form-item>
        </template>
        <template v-if="loopType === 2">
          <el-form-item label="指定星期：" prop="triggerWeekAssignDate" :rules="[{ required: true, message: '请选择指定星期', trigger: 'change' }]">
            <el-checkbox :indeterminate="isWeekIndeterminate" v-model="checkAllWeek" @change="handleCheckAllWeek">全选</el-checkbox>
            <el-checkbox-group v-model="triggerTimeForm.triggerWeekAssignDate" @change="handleCheckedWeeksChange">
              <el-checkbox v-for="item in weeks" :label="item.id" :key="item.id">{{item.week}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>
        <template v-if="loopType === 3">
          <el-form-item label="指定日期：" prop="triggerMonthAssignDate" :rules="[{ required: true, message: '请选择指定日期', trigger: 'change' }]">
            <el-checkbox :indeterminate="isMonthIndeterminate" v-model="checkAllMonth" @change="handleCheckAllMonths">全选</el-checkbox>
            <el-checkbox-group v-model="triggerTimeForm.triggerMonthAssignDate" @change="handleCheckedMonthsChange">
              <el-checkbox v-for="item in months" :label="item.id" :key="item.id">{{item.month}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>
        <template v-if="loopType !== 0">
          <el-form-item label="开始日期：" prop="triggerStartDate" :rules="[{ required: true, message: '请选择开始日期', trigger: 'change' }]">
            <el-date-picker
              v-model="triggerTimeForm.triggerStartDate"
              type="date"
              placeholder="选择开始日期"
              size="small"
              style="width: 65%"
              :disabled="shareData.isDisable"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item label="结束日期：" class="end-date">
            <el-radio v-model="triggerTimeForm.triggerEndDateType" :label="0" @change="handleChange">永不过期</el-radio>
            <el-radio v-model="triggerTimeForm.triggerEndDateType" :label="1" class="radio-warp" @change="handleChange">
              <el-form-item prop="triggerEndDate" :rules="[{ required: triggerTimeForm.triggerEndDateType === 1 ? true : false, message: '请选择结束日期', trigger: 'change' }]">
                <el-date-picker
                  v-model="triggerTimeForm.triggerEndDate"
                  type="date"
                  placeholder="选择结束日期"
                  size="small"
                  style="width: 80%"
                  :disabled="shareData.isDisable"
                  :picker-options="pickerOptions"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  @focus="handleEndDateFocus"
                  @change="handleChange"
                />
              </el-form-item>
            </el-radio>
          </el-form-item>
        </template>
        <el-form-item label="时间类型：" prop="triggerTimeType">
          <el-select
            placeholder="请选择时间类型"
            filterable
            v-model="triggerTimeForm.triggerTimeType"
            :disabled="shareData.isDisable"
            size="small"
            style="width: 65%"
            @change="handleChange"
          >
            <el-option label="时间点" :value="0"></el-option>
            <el-option label="时间段" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <div v-show="triggerTimeForm.triggerTimeType === 0">
          <el-form-item label="指定时间：">
            <div class="time-point" v-for="(item, index) in triggerTimeForm.triggerTimePointValues" :key="index">
              <el-form-item :style="item.deleteFlag && item.deleteFlag === 1 ? {display: 'none'} : {}" :prop="'triggerTimePointValues.' + index + '.timeValue'" :rules="[{ required: true, message: '请选择时间点', trigger: 'change' }]">
                <el-time-picker
                  v-model="item.timeValue"
                  placeholder="请选择时间点"
                  :disabled="shareData.isDisable"
                  size="small"
                  style="width: 65%"
                  format="HH:mm"
                  value-format="HH:mm"
                  @change="handleChange"
                />
                <template v-if="!shareData.isDisable">
                  <span :style="item.deleteFlag && item.deleteFlag === 1 ? {display: 'none'} : {}" @click="handleTimeAdd('时间点')" class="icon-add"><i class="el-icon-circle-plus"/></span>
                  <span :style="item.deleteFlag && item.deleteFlag === 1 ? {display: 'none'} : {}" v-if="index" @click="handleTimeDel('时间点', item, index)" class="icon-delete"><i class="el-icon-remove"/></span>
                </template>
              </el-form-item>
            </div>
          </el-form-item>
        </div>
        <div v-show="triggerTimeForm.triggerTimeType === 1">
          <el-form-item label="指定时间：">
            <div class="time-point" v-for="(item, index) in triggerTimeForm.triggerTimeRangeValues" :key="index">
              <el-form-item :style="item.deleteFlag && item.deleteFlag === 1 ? {display: 'none'} : {}" :prop="'triggerTimeRangeValues.' + index + '.timeValue'" :rules="[{ required: true, message: '请选择时间范围', trigger: 'change' }]">
                <el-time-picker
                  is-range
                  v-model="item.timeValue"
                  range-separator="~"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                  :disabled="shareData.isDisable"
                  size="small"
                  style="width: 65%"
                  format="HH:mm"
                  value-format="HH:mm"
                  @change="handleChange"
                />
                <template v-if="!shareData.isDisable">
                  <span :style="item.deleteFlag && item.deleteFlag === 1 ? {display: 'none'} : {}" @click="handleTimeAdd('时间范围')" class="icon-add"><i class="el-icon-circle-plus"/></span>
                  <span :style="item.deleteFlag && item.deleteFlag === 1 ? {display: 'none'} : {}" v-if="index" @click="handleTimeDel('时间范围', item, index)" class="icon-delete"><i class="el-icon-remove"/></span>
                </template>
              </el-form-item>
            </div>
          </el-form-item>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
// 校验表单子弹
const rules = {
  triggerAssignDate: [{ required: true, message: '请选择日期', trigger: 'change' }],
  triggerTimeType: [{ required: true, message: '请选择时间类型', trigger: 'change' }]
}
export default {
  name: 'TriggerTimeForm',
  inject: ['shareData'],
  props: {
    loopType: {
      type: Number,
      default: 0
    },
    modelValue: {
      type: Object
    }
  },
  model: {
    prop: 'modelValue',
    event: 'change'
  },
  data () {
    return {
      rules,
      pickerOptions: {
        disabledDate (time) {
          return time < Date.now() - 86400000
        }
      },
      checkAllWeek: false,
      isWeekIndeterminate: false,
      checkAllMonth: false,
      isMonthIndeterminate: false,
      weeks: [
        { id: 1, week: '星期一' },
        { id: 2, week: '星期二' },
        { id: 3, week: '星期三' },
        { id: 4, week: '星期四' },
        { id: 5, week: '星期五' },
        { id: 6, week: '星期六' },
        { id: 7, week: '星期日' }
      ],
      months: [],
      triggerTimeForm: {
        triggerAssignDate: '',
        triggerTimeType: 0,
        triggerStartDate: '',
        triggerWeekAssignDate: [],
        triggerMonthAssignDate: [],
        triggerEndDate: '',
        triggerEndDateType: 0,
        triggerTimePointValues: [{ timeValue: '09:00' }],
        triggerTimeRangeValues: [{ timeValue: ['09:00', '18:00'] }] // 必须设置默认的时间，不然无法进行时间的选择，组件里显示的为空数据
      }
    }
  },
  watch: {
    loopType: {
      immediate: true,
      handler () {
        this.handleLoopType()
      }
    },
    'triggerTimeForm.triggerWeekAssignDate': {
      immediate: true,
      deep: true,
      handler () {
        if (this.triggerTimeForm.triggerWeekAssignDate?.length) {
          this.checkAllWeek = this.triggerTimeForm.triggerWeekAssignDate.length === this.weeks.length
          this.isWeekIndeterminate = this.triggerTimeForm.triggerWeekAssignDate.length > 0 && this.triggerTimeForm.triggerWeekAssignDate.length < this.weeks.length
        }
      }
    },
    'triggerTimeForm.triggerMonthAssignDate': {
      immediate: true,
      deep: true,
      handler () {
        if (this.triggerTimeForm.triggerMonthAssignDate?.length) {
          this.checkAllMonth = this.triggerTimeForm.triggerMonthAssignDate.length === this.months.length
          this.isMonthIndeterminate = this.triggerTimeForm.triggerMonthAssignDate.length > 0 && this.triggerTimeForm.triggerMonthAssignDate.length < this.months.length
        }
      }
    }
  },
  methods: {
    handleTimeAdd (type) {
      if (type === '时间点') {
        // 指定时间点添加
        this.triggerTimeForm.triggerTimePointValues.push({ timeValue: '09:00' })
      } else if (type === '时间范围') {
        // 指定时间范围添加
        this.triggerTimeForm.triggerTimeRangeValues.push({ timeValue: ['09:00', '18:00'] })
      }
      this.handleChange()
    },
    handleTimeDel (type, item, index) {
      if (type === '时间点') {
        // 指定时间点删除
        if (item.id) {
          this.triggerTimeForm.triggerTimePointValues[index].deleteFlag = 1
        } else {
          this.triggerTimeForm.triggerTimePointValues.splice(index, 1)
        }
      } else if (type === '时间范围') {
        // 指定时间范围删除
        if (item.id) {
          this.triggerTimeForm.triggerTimeRangeValues[index].deleteFlag = 1
        } else {
          this.triggerTimeForm.triggerTimeRangeValues.splice(index, 1)
        }
      }
      this.handleChange()
    },
    handleCheckAllWeek (val) {
      this.triggerTimeForm.triggerWeekAssignDate = val ? this.weeks.map(n => n.id) : []
      this.isWeekIndeterminate = false
      this.handleChange()
    },
    handleCheckedWeeksChange (val) {
      this.checkAllWeek = val.length === this.weeks.length
      this.isWeekIndeterminate = val.length > 0 && val.length < this.weeks.length
      this.handleChange()
    },
    handleCheckAllMonths (val) {
      this.triggerTimeForm.triggerMonthAssignDate = val ? this.months.map(n => n.id) : []
      this.isMonthIndeterminate = false
      this.handleChange()
    },
    handleCheckedMonthsChange (val) {
      this.checkAllMonth = val.length === this.months.length
      this.isMonthIndeterminate = val.length > 0 && val.length < this.months.length
      this.handleChange()
    },
    handleEndDateFocus () {
      this.triggerTimeForm.triggerEndDateType = 1
    },
    handleChange () {
      this.$emit('change', this.triggerTimeForm)
    },
    handleLoopType () {
      // 切换循环类型，指定日期，时间类型，指定时间等初始化
      if (this.loopType === 0) {
        // 单次
        this.resetTime()
      } else if (this.loopType === 1) {
        // 每天
        this.resetTime()
      } else if (this.loopType === 2) {
        // 每周
        this.resetTime()
      } else if (this.loopType === 3) {
        // 每月
        this.resetTime()
      }
    },
    resetTime () {
      this.triggerTimeForm.triggerAssignDate = ''
      this.triggerTimeForm.triggerTimeType = 0
      this.triggerTimeForm.triggerStartDate = ''
      this.triggerTimeForm.triggerEndDate = ''
      this.triggerTimeForm.triggerEndDateType = 0
      this.triggerTimeForm.triggerWeekAssignDate = []
      this.isWeekIndeterminate = false
      this.checkAllWeek = false
      this.triggerTimeForm.triggerMonthAssignDate = []
      this.isMonthIndeterminate = false
      this.checkAllMonth = false
      this.handleSwithTimeType()
    },
    handleSwithTimeType () {
      // 切换事件类型把时间点和时间范围初始化
      if (this.triggerTimeForm.triggerTimeType === 0) {
        this.triggerTimeForm.triggerTimePointValues = this.triggerTimeForm.triggerTimePointValues.filter((n, i) => i === 0)
        this.triggerTimeForm.triggerTimePointValues[0].timeValue = '09:00'
      } else if (this.triggerTimeForm.triggerTimeType === 1) {
        this.triggerTimeForm.triggerTimeRangeValues = this.triggerTimeForm.triggerTimeRangeValues.filter((n, i) => i === 0)
        this.triggerTimeForm.triggerTimeRangeValues[0].timeValue = ['09:00', '18:00']
      }
    },
    getMonthsData () {
      // 获取31天
      for (let i = 1; i < 32; i++) {
        this.months.push({
          id: i,
          month: i < 10 ? `0${i}` : `${i}`
        })
      }
    }
  },
  mounted () {
    this.getMonthsData()
    if (this.shareData.title !== '新增自定义告警') {
      this.triggerTimeForm = { ...this.triggerTimeForm, ...this.modelValue }
    }
  }
}
</script>
<style lang="scss" scoped>
.trigger-time-form {
  .time-point {}
  .end-date {
    ::v-deep {
      .el-form-item__content {
        display: flex;
        align-items: center;
      }
    }
    .radio-warp {
      display: flex;
      align-items: center;
    }
  }
  ::v-deep {
    .el-form-item {
      margin-bottom: 0;
      .el-form-item__content {
        .el-form-item__error {
          padding-top: 0;
        }
        margin-bottom: 10px;
      }
    }
  }
  .icon-add, .icon-delete {
    cursor: pointer;
    display: inline-block;
    line-height: 40px;
    margin-top: 4px;
    & > i {
      font-size: 24px;
    }
  }
  .icon-add {
    color: #1ae1e6;
  }
  .icon-delete {
    margin-left: 4px;
    color: #F56C6C;
  }
}
</style>
